//
//  MyMoneyViewController.m
//  JiongTu
//
//  Created by Dupengfei on 16/4/11.
//  Copyright © 2016年 YSKJ. All rights reserved.
//

#import "MyMoneyViewController.h"
#import "MyMoneyTableViewCell.h"
#import <AVQuery.h>
#import "JTUser.h"
#import <AVUser.h>
#import <SVProgressHUD.h>
#import <AVObject.h>
#import <AVOSCloud.h>
@interface MyMoneyViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *button;
@property (nonatomic, strong)NSString * day;
@property (nonatomic, strong)NSString * priceDay;

@end

@implementation MyMoneyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _tableView.delegate =self;
    
    _tableView.dataSource =self;
    
    self.title =@"我的钱包";
    
    [self getServerDate];
    }

-(void)getServerDate
{
    dispatch_queue_t queue = dispatch_queue_create("Q", NULL);
    
    dispatch_async(queue, ^{
        NSDate * date =[AVOSCloud getServerDate:nil];
        NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
        formatter.dateFormat=@"yyyy年MM月dd日";
        _priceDay =[formatter stringFromDate:date];
        _day=[[[formatter stringFromDate:date] substringFromIndex:8]substringToIndex:2];
    });

}

-(void)viewDidLayoutSubviews
{
    _tableView.rowHeight = _tableView.frame.size.height/2;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [SVProgressHUD dismiss];
}

#pragma mark-delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyMoneyTableViewCell*cell = [[[NSBundle mainBundle] loadNibNamed:@"MyMoneyTableViewCell" owner:nil options:nil] lastObject];
    switch (indexPath.row) {
        case 0:
        {
            cell.image.image = [UIImage imageNamed:@"我的钱包_03"];
            cell.moeny.text = @"   我的余额：";
            
            dispatch_queue_t queue = dispatch_queue_create("Q", NULL);
            [SVProgressHUD showWithStatus:@"查询中"];
                dispatch_async(queue, ^{
                    [[AVUser currentUser] fetchInBackgroundWithBlock:^(AVObject *object, NSError *error) {
                        if (!error) {
                            JTUser *currentUser = [JTUser userWithCurrentUser:object];
                            [currentUser save];
                            
                            cell.numberOfmoney.text = [NSString stringWithFormat:@"%@元",[JTUser currentUser].sumMoney];
                            [SVProgressHUD showSuccessWithStatus:@"查询完成"];
                        }
                    }];
                            });
        }
            break;
            
        case 1:
        {
            cell.image.image =[UIImage imageNamed:@"我的钱包_06"];
            cell.moeny.text  =@"   支付宝提现";
        }
            break;
        default:
            break;
    }
   
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 1:
        {
            if ([_day intValue]<28 && [[JTUser currentUser].sumMoney intValue]>0)
            {
                [SVProgressHUD showErrorWithStatus:@"现在不是提现时间!"];
            }
            else{
            UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"请输入提现金额" message:@"" preferredStyle:UIAlertControllerStyleAlert];
            [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {

                textField.clearButtonMode = UITextFieldViewModeWhileEditing;
                
                textField.textAlignment = NSTextAlignmentCenter;
                
                textField.keyboardType =UIKeyboardTypeNumberPad;
                
            }];

            UIAlertAction * action =[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
               
                UITextField * textFiled =alert.textFields[0];
                
                if ([textFiled.text intValue]>[[JTUser currentUser].sumMoney intValue]) {
                    
                    [SVProgressHUD showErrorWithStatus:@"提现金额大于您的余额!"];
                }
                else if ([textFiled.text isEqualToString:@""])
                {
                    NSLog(@"空");
                }
                else
                {
                    int money  = ([[JTUser currentUser].sumMoney intValue]-[textFiled.text intValue]);
                    
                    NSNumber * mySum = [NSNumber numberWithInt:money];
                    
                    JTUser * user =[JTUser currentUser];
                    
                    user.sumMoney = mySum;
                    
                    [user save];
                    
                    AVObject * myselyMoney = [AVObject objectWithoutDataWithClassName:@"_User" objectId:[AVUser currentUser].objectId];
                    
                    [myselyMoney setObject:mySum forKey:@"Sum"];
                    
                    [SVProgressHUD showWithStatus:@"正在获取数据。。。"];
                    
                    [myselyMoney saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        if (succeeded) {
                            NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
                            [dict setObject:user.mobilePhoneNumber forKey:@"phoneNumber"];
//                            [dict setObject:_priceDay forKey:@"payment_create_time"];
                            [dict setObject:textFiled.text forKey:@"money"];
//                            [dict setObject:[NSString stringWithFormat:@"%@元",mySum] forKey:@"price"];
                            
                            [AVOSCloud requestSmsCodeWithPhoneNumber:@"13136002600" templateName:@"company Pay To Driver" variables:dict callback:^(BOOL succeeded, NSError *error) {
                                if (succeeded) {
                                } else {
                                    NSLog(@"%@", error);
                                }
                            }];
                            
                            [SVProgressHUD showSuccessWithStatus:@"提现成功，将在24小时内转账到你的支付宝账户中！"];
                            
                            [self.tableView reloadData];
                        }
                        else
                        {
                            [SVProgressHUD showErrorWithStatus:@"网络问题，请重试！"];
                        }
                        
                    }];
                    
                   
                                  }
            }];
            
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
            }
        }
            break;
            
        default:
            break;
    }
}

- (IBAction)buttonPressed:(UIButton *)sender {
    NSString * string =@"1.为了保证你账户的安全，须实名实车认证后方可实现余额提现。                                                       2.提现支付宝用户名称应与实名实车认证姓名一致;每次最多体现5000元                                                             3.余额提现可在该月月底最后两天提现。                                                                                  4.到账时间：所有提现将在提现后的48小时内到账。";
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"囧途用户提现规则" message:string preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * action =[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}


@end
